﻿//*************************************************************************************
//* 作    者： 邹杭特
//* 创建时间： 2021-12-03 19:00:39
//* 描    述：  

//* ************************************************************************************
using System;
using UnityEngine;
using UFrame.NetSocket;
using Google.Protobuf;

public class GooglePbNetSerialiser : IPacketSerialiser
{
    public T Deserialise<T>(byte[] packetBytes, int offset, int length)
    {
        using (var cos = new CodedInputStream(packetBytes, offset, length))
        {
            var messageBody = System.Activator.CreateInstance(typeof(T));
            if (messageBody is IMessage)
                cos.ReadMessage(messageBody as IMessage);
            return (T)messageBody;
        }
    }

    public byte[] Serialize<T>(T packet)
    {
        IMessage message = (IMessage)(object)packet;
        byte[] data = new byte[message.CalculateSize()];
        using (var cos = new CodedOutputStream(data))
        {
            message.WriteTo(cos);
        }
        return data;
    }
}
